package org.zjut.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjut.db.CourseDataBase;
import org.zjut.db.RcommondDataBase;
import org.zjut.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Rising
 * @date 2017/9/24
 * @des
 */
@Controller
public class RecommondController {
    @Autowired
    RcommondDataBase rcommondDataBase;
    @Autowired
    CourseDataBase courseDataBase;


    /**
     * 完成某个资源的学习
     * @param request
     * @return
     */
    @RequestMapping(value = "/finishResource", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String finishResource(HttpServletRequest request){
        JSONObject params =null;
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }else{
            params = JSON.parseObject(CommonUtil.getBodyRequest(request));

        }
        try {
           rcommondDataBase.finishResource(params.get("userCode").toString(),params.get("resourceCode").toString());
            Map<String,Object> result = new HashMap<>();
            result.put("success",true);
            result.put("message","请求成功");
           return JSON.toJSONString(request);
        }catch (Exception e){
            return JSON.toJSONString(CommonUtil.setErrorInfo("完成失败"));
        }
    }


    /**
     * w完成某门课程
     * @param request
     * @return
     */
    @RequestMapping(value = "/finishCourse", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String finishCourse(HttpServletRequest request){
        JSONObject params =null;
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }else{
            params = JSON.parseObject(CommonUtil.getBodyRequest(request));
        }

        try {
            //先获取课程ID
            Map<String,Object> courseInfo = courseDataBase.getLearningCourse(params.get("userCode").toString());
            rcommondDataBase.finishCourse(params.get("userCode").toString(),courseInfo.get("courseCode").toString());
            Map<String,Object> result = new HashMap<>();
            result.put("success",true);
            result.put("message","请求成功");
            return JSON.toJSONString(result);
        }catch (Exception e){
            System.out.println("finishCourse:"+e.getMessage());
            return JSON.toJSONString(CommonUtil.setErrorInfo("完成失败"));
        }
    }
}
